<?php
$appkey = "e0ca9f6f759c8538";
$salt = "51bc4c807922e366ea4fb80f111e8d70"; // sign 验证用的加密盐。
$errorVideo = "/api/404.mp4"; // 解析失败时返回的视频地址。

/**
 * real IP
 *
 * @access  public
 * @return  string
 */
	function real_ip() {
		static $realip = NULL;
		if ($realip !== NULL) {
			return $realip;
		}
		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
				/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
				foreach ($arr AS $ip) {
					$ip = trim($ip);
					if ($ip != 'unknown') {
						$realip = $ip;
						break;
					}
				}
			}
			elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$realip = $_SERVER['HTTP_CLIENT_IP'];
			} else {
				if (isset($_SERVER['REMOTE_ADDR'])) {
					$realip = $_SERVER['REMOTE_ADDR'];
				} else {
					$realip = '0.0.0.0';
				}
			}
		} else {
			if (getenv('HTTP_X_FORWARDED_FOR')) {
				$realip = getenv('HTTP_X_FORWARDED_FOR');
			} elseif (getenv('HTTP_CLIENT_IP')) {
				$realip = getenv('HTTP_CLIENT_IP');
			} else {
				$realip = getenv('REMOTE_ADDR');
			}
		}
		preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
		$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
		return $realip;
	}

	function curl_get_contents($url){   
		$ch = curl_init();   
		curl_setopt($ch, CURLOPT_URL, $url);   
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		$ip = isset($_SERVER['HTTP_ALI_CDN_REAL_IP']) ? $_SERVER['HTTP_ALI_CDN_REAL_IP'] : $_SERVER['REMOTE_ADDR'];
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Forwarded-For: '.$ip, 'Client-IP: '.$ip));
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 
		//curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
		$r = curl_exec($ch);
		curl_close($ch);
		return $r;
	}
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {    
    $ckey_length = 4;   
    $key = md5($key);  
    if($operation == "DECODE") { $string = strtolower($string); } 
    $keya = md5(substr($key, 0, 16));   
    $keyb = md5(substr($key, 16, 16));   
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';    
    $cryptkey = $keya.md5($keya.$keyc);   
    $key_length = strlen($cryptkey);   
    $string = $operation == 'DECODE' ? hex2bin(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;   
    $string_length = strlen($string);   
    $result = '';   
    $box = range(0, 255);   
    $rndkey = array();    
    for($i = 0; $i <= 255; $i++) {   
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);   
    }   
    for($j = $i = 0; $i < 256; $i++) {   
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;   
        $tmp = $box[$i];   
        $box[$i] = $box[$j];   
        $box[$j] = $tmp;   
    }   
    for($a = $j = $i = 0; $i < $string_length; $i++) {   
        $a = ($a + 1) % 256;   
        $j = ($j + $box[$a]) % 256;   
        $tmp = $box[$a];   
        $box[$a] = $box[$j];   
        $box[$j] = $tmp;   
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));   
    }   
    if($operation == 'DECODE') {  
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {   
            return substr($result, 26);   
        } else {   
            return '';   
        }   
    } else {   
        return strtoupper($keyc.bin2hex($result));   
    }   
}
/* 如果有 xmlurl 参数即为 ckxml，有 h5url 参数即为 html5。 这两个参数均可以直接传递 url，也可以设置为 null 然后通过 type+vid 传递，例如：xmlurl=null&type=youku&vid=XODk1MjczMjky */
if(isset($_REQUEST['h5url'])){
	$format = "html5";
	$url = urldecode($_REQUEST['h5url']);
}elseif(isset($_REQUEST['xmlurl'])){
	$format = "ckxml";
	$url = urldecode($_REQUEST['xmlurl']);
}else{
	exit("需要视频地址。 Need URL.");
}

if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']!=""){
	$purl = parse_url($_SERVER['HTTP_REFERER']);
	$hos = explode(".", $purl['host']);
	$ok = false;
	if( $hos[count($hos)-2] == "1haza" && $hos[count($hos)-1] == "com" ){
		$ok = true;
	}
	if(!$ok){
		header('HTTP/1.1 403 Forbidden');
		exit("pirate");
	}
}else{
	header('HTTP/1.1 403 Forbidden');
	exit("pir");
}

$devid = authcode($_REQUEST['vid'], 'DECODE', '531d69663e14831e5fa04b24b8a6e5ea');
if(substr($devid, 0, 4) == "http"){
	$_REQUEST['url'] = $_REQUEST['vid'];
	unset($_REQUEST['vid']);
	unset($_REQUEST['type']);
}

if(isset($_REQUEST['url'])){
	$url = urldecode($_REQUEST['url']);
}

$vpara = $url == "null" ? $_REQUEST['vid'] : $url;
if(isset($_REQUEST['tm']) && isset($_REQUEST['sign']) && $_REQUEST['tm'] && $_REQUEST['sign']){
	$_tm = $_REQUEST['tm'];
	$_sign = $_REQUEST['sign'];
	if($_sign != md5($_tm . '~' . $vpara . '~' . $salt)){ // sign 错误。
		header('HTTP/1.1 403 Forbidden');
		exit("error sign");
	}elseif(time() - $_tm > (isset($_REQUEST['hd']) ? 14400 : 60)){ // tm 超过 4 小时。
		header('HTTP/1.1 403 Forbidden');
		exit("expired sign");
	}
}else{
	header('HTTP/1.1 403 Forbidden');
	exit("sign required");
}

if(isset($_REQUEST['mobile']) && $_REQUEST['mobile']=="1"){
	$format = "html5";
}



if(substr($url, 0, 4) != "http" && stristr($url,"_")){ // url=XODk1MjczMjky_youku 这种格式。
	$_a = explode("_",$url);
	$type = $_a[1];
	$vid = $_a[0];
}

if(isset($_REQUEST['type']) && isset($_REQUEST['vid'])){
	$type = $_REQUEST['type'];
	$vid = $_REQUEST['vid'];
}

$hd = isset($_REQUEST['hd'])?intval($_REQUEST['hd']):2; // 默认清晰度

$userlink = isset($_REQUEST['userlink'])?"&userlink={$_REQUEST['userlink']}":"";

/*
	下面是规则改变区域，如果你保存的类型缩写和我们的标准不一样，请在下方 changeList 中修改。
	例如：我们的标准中，乐视云的缩写是“letvcloud”，而你保存的却是“yun”，就可以 "yun" => "letvcloud" 。
	最后一个规则后面不要加逗号。
*/
if(isset($type)){
	$changeList = array(
		"letvcom" => "letv",
		"yun" => "letvcloud",
		"swf" => "cntv",
		"hd_iask" => "sina",
		"hd_56" => "56",
		"qiyi" => "iqiyi",
		"yuku" => "youku",
		"pvod" => "pptv",
		"ibilibili" => "bilibili"
	);
	foreach($changeList as $cfrom=>$cto){
		if($type==$cfrom){
			$type = $cto;
		}
	}

	/* 下面是 vid 改造区，请使用 php 代码对 $vid 进行改变。 */

}else{
	/* 如果是 url 模式，你可以在这个 else 区域里面对 $url 进行判断和改造 */
	
}

if(isset($type)){
	$devid = authcode($vid, 'DECODE', '531d69663e14831e5fa04b24b8a6e5ea');
	$requests = "type={$type}&vid={$devid}";
	$enrequests = "type={$type}&vid={$vid}";
	$tm = time();
	$sign = md5($tm . '~' . $vid . '~' . $salt);
}else{
	$deurl = authcode($url, 'DECODE', '531d69663e14831e5fa04b24b8a6e5ea');
	$requests = "url=".urlencode($deurl);
	$enrequests = "url=".urlencode($url);
	$tm = time();
	$sign = md5($tm . '~' . $url . '~' . $salt);
}
if($type == "acku"){ $_REQUEST['mp4'] = 1; unset($_REQUEST['m3u8']); }
$h2d = array(0 => "fsd", 1 => "sd", 2 => "hd", 3 => "shd", 4 => "fhd", 5 => "fhd", 6 => "fhd", 7 => "fhd");
$definition = $h2d[$hd];
if($format=="html5"){
	if(isset($_REQUEST['m3u8']) && $_REQUEST['m3u8']){ $requests.= "&ext=m3u8"; }
	if(isset($_REQUEST['mp4']) && $_REQUEST['mp4']){ $requests.= "&ext=mp4"; }
	$api_url = "http://parsev.bceapp.com/vp/open.php?appkey={$appkey}&format=json&mode=single&method=direct&{$requests}&definition={$definition}{$userlink}";
	if(isset($_REQUEST['script']) && $_REQUEST['script']){
		$api_url.= "&format=js&div=player";
		header('Content-type: text/javascript; charset=utf-8');
		$api_js = curl_get_contents($api_url);
		// $api_js = str_replace("//customCode1", "vP.poster = '图片地址';", $api_js);
		exit($api_js);
	}
	$api_json = curl_get_contents($api_url);
	$api = json_decode($api_json, true);
	if(isset($api['result']['files'][0]['url'])){
		$video = $api['result']['files'][0]['url'];
	}else{
		$video = $errorVideo;
	}
    if(isset($_REQUEST['ajax']) && $_REQUEST['ajax']){
        exit($video);
    }else{
        header("Location: {$video}");
    }
	exit;
}elseif($format=="ckxml"){
	$http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
	$def = "{$http}://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}?xmlurl=null&["."$"."pat]&tm={$tm}&sign={$sign}";
	$modeText = "mode=part";
	if(isset($_REQUEST['m3u8']) && $_REQUEST['m3u8']){ $modeText = "mode=single&ext=m3u8"; $def = str_replace("xmlurl=", "h5url=", $def); }
	$def = urlencode($def);
	$api = "http://parsev.bceapp.com/vp/open.php?appkey={$appkey}&format=ckxml&{$modeText}&method=direct&{$requests}&definition={$definition}{$userlink}&def={$def}";
	$data = curl_get_contents($api);
	$data = str_replace($requests, $enrequests, $data);
	$data = strtr($data, array("标清" => "360P", "高清" => "540P", "超清" => "720P", "原画" => "1080P"));
	header('Content-type: text/xml; charset=utf-8');
	if(stristr($data,"<ckplayer/>")){
		exit('<?xml version="1.0"?><ckplayer><flashvars>{h->1}</flashvars><video><file><![CDATA[' . $errorVideo . ']]></file><size>0</size><seconds>0</seconds></video></ckplayer>');
	}
	exit($data);
}
exit;
?>